package com.mg.g2048;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import com.mg.g2048.SD.SDHelper;

public class InternetHelper {

	
	/**
	 * 下载文件，软件更新使用
	 * 该文件已存在，则直接获取其 File 覆盖之
	 * @return 
	 */
	public static boolean getFile(Context context,String SDPath,String uri){
		File file = null;
		// 该文件已存在，则直接获取其File，覆盖之
		if (SDHelper.exists(SDPath))
			file = new File(SDPath);
		else
			file = SDHelper.createFile(SDPath);
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection();
			InputStream input = conn.getInputStream();
			if (null != input) {
				OutputStream output = new FileOutputStream(SDPath);
				byte[] buffer = new byte[1024];
				int i = 0;
				while ((i = input.read(buffer)) != -1) {
					output.write(buffer, 0, i);
				}
				output.flush();
				output.close();
				input.close();
				conn.disconnect();
				Intent intent = new Intent();  
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
				intent.setAction(android.content.Intent.ACTION_VIEW);  
				intent.setDataAndType(Uri.fromFile(file),  
								"application/vnd.android.package-archive");  
				context.startActivity(intent);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
